<?php

namespace app\api\controller\feiyu;


use app\admin\library\Auth;
use app\common\exception\UploadException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Config;
use think\exception\PDOException;
use think\Hook;
use baiying\lib\BYTokenClient;
use think\Db;

/**
 * 公共接口
 */
class Bidui extends Base {

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize() {
        parent::_initialize();
    }


    public function import()
    {

        $request_data = $this->request->param();

        $filePath = ROOT_PATH . DS . 'public' . DS . '1.xlsx';
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
//        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
//
//        $table = $this->model->getQuery()->getTable();
//        $database = \think\Config::get('database.database');
//        $fieldArr = [];
//        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
//        foreach ($list as $k => $v) {
//            if ($importHeadType == 'comment') {
//                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
//                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
//            } else {
//                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
//            }
//        }
        $jobid  = empty($request_data['jobid']) ? 0 : $request_data['jobid'];
        if(empty($jobid)){
            $this->error('jobid 为空');
        }
        $list = db(getBaiYingDataTable())->where([
            'createtime'=>['>',strtotime('today')],
            'callJobId'=>$jobid,
            'yixiang_value'=>['in',['A','B']],
        ])->column('callInstanceId');

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

            $err_data = [];

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = (string)(is_null($val) ? '' : $val);
                }


                if ($values) {
                    if(!in_array($values[0],$list)){
                        $err_data[] = [
                            'callInstanceId'=>$values[0],
//                            'mobile'=>$values[2],
//                            'starttime'=>$values[10],
                        ];
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('',[count($err_data),implode(',',array_column($err_data, 'callInstanceId'))]);

    }








}
